/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbHash.cpp			*/
/********************************************************/

#include "GlbHash.h"

namespace GlbIpc
{

CGlbHash::CGlbHash()
{
	m_ulHash = 0;
}

CGlbHash::~CGlbHash()
{
	m_ulHash = 0;
}

void CGlbHash::GlbHashDelete()
{
	CGlbShm::GlbIpcDelete();

	return;
}

int CGlbHash::GlbHashCreate(key_t iKey, ULONG ulHash)
{
	int iReturn = GLB_SUCCESS;

	if (GLB_SUCCESS == CGlbShm::GlbIpcCreate(iKey, ulHash * sizeof(void*))) {
		CGlbShm::GlbShmReset(ulHash * sizeof(void*));
		m_ulHash = ulHash;
	}
	else {
		iReturn = GLB_FAILURE;
	}

	return iReturn;
}

ULONGLONG CGlbHash::GlbHashFunction(char* pszKey, UINT uiLength)
{
	UINT uiIndex = 0;
	ULONGLONG ullReturn = 0;

	ullReturn = GLB_BASIC * uiLength;
	for (; uiIndex < uiLength; uiIndex ++) {
		ullReturn = (ullReturn + (*(pszKey + uiIndex) << (uiIndex * 13 % 24))) & GLB_MASK;
	}

	return (GLB_OFFSET * ullReturn + GLB_PLUS) & GLB_MASK;  
}

void CGlbHash::GlbHashPutBucket(ULONGLONG ullKey, void** ppKey)
{
	void** ppBucket = NULL;

	ppBucket = (void**)GlbHashGetBucket(ullKey % m_ulHash);
	memcpy(ppBucket, ppKey, sizeof(void*));

	return;
}

} /* GlbIpc */
